<template>
    <div class="upload-image-container">
        <div class="row">
            <div class="col">
                <h6 class="title">
                    <small class="text-mute">允许上传文件格式：{{ extensions }}</small>
                    <!--<small class="pull-right">您至少需要上传{{ min }} 个文件，还可以上传 {{ filesLeft }} 个文件.-->
                    </small>
                </h6>
            </div>
        </div>

        <draggable v-model="filelist" :options="{draggable:'.item'}" @change="changeSort()" class="d-flex flex-wrap upload-file-list">
            <uploaded-file-item v-for="element in filelist" class="item" :key="element.id" :item="element" @preview="onPreview"  @remove="onRemove">
            </uploaded-file-item>

            <uploaded-file-item v-show="uploadingFile !== null"
                                :percentage="uploadingFile?uploadingFile.percentage:0">
            </uploaded-file-item>
            <div>
                <el-upload
                        v-if="filelist.length < options.max"
                        :action="uploadAction"
                        list-type="picture-card"
                        :data="uploadFormParams"
                        :accept="options.ext"
                        :on-preview="handlePictureCardPreview"
                        :before-upload="onBeforeUpload"
                        :on-success="onSuccess"
                        :on-progress="onUploadProgress"
                        :on-error="onError"
                        :show-file-list="false">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </div>
        </draggable>
    </div>

</template>
<script>

  import ReportApi from 'assets/js/api/report'
  import md5 from 'blueimp-md5'
  import util from 'assets/js/libs/util'
  import draggable from 'vuedraggable'
  import UploadedFileItem from '../works/UploadedFileItem'
  // import propsync from 'assets/js/libs/propsync';
  export default {
    components: {
      draggable,
      UploadedFileItem
    },
    // mixins: [propsync],
    props: {
      options: {
        type: Object,
        default:
          {
            'title': '上传图片',
            'key': '内容',
            'exts': '.jpg',
            'min': 1,
            'max': 1,
          }
      },
      min: {
        type: Number,
        propsync:false,
        default: 1
      },
      max: {
        type: Number,
        default: 1
      },
      exts: {
        type: String,
        default: '*'
      },
      fileList: {
        type: Array,
        default: []
      },
      worksId: {
        type: Number,
        default: 0
      }

    },
    data () {
      return {
        filelist:this.fileList,
        dialogImageUrl: '',
        dialogVisible: false,
        uploadFormParams: {
          'key': '', //path
          'policy': '', //OssUtilities.signature.policy
          'OSSAccessKeyId': '', //OssUtilities.signature.accessid
          'success_action_status': '200', //让服务端返回200,不然，默认会返回204
          'callback': '',//OssUtilities.signature.accessid
          'signature': '' //OssUtilities.signature.signature
        },
        uploadAction: '',
        height:16384,
        uploadingFile: null
      }
    },
    computed: {
      extensions () {
        let exts = this.exts.split(',')
        exts.forEach((element, index) => {
          if (element.indexOf('.') === -1) {
          exts[index] = '.' + exts[index]
        }
      })
        return exts.join(',')
      },
      filesLeft () {
        return Number.parseInt(this.max) - this.fileList.length
      }
    },
    methods: {
      /**
       *
       */
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      /**
       *
       */
      onError (e) {
        console.log(e)
      },
      /**
       *
       * @param file
       * @returns {Promise<never>}
       */
      async onBeforeUpload (file) {
    let self = this
    let reader = await util.readFileAsDataURL(file)
    let isJPG = false
    let image = new Image()
    image.src = reader.result
    let allow = self.exts.split(',')
        console.log(allow)
    if(allow.length>1){
      allow.forEach((item)=>{
      if (file.name.split('.')[1].toLowerCase() === item){
        isJPG = true
      }
    })
    }else{
      if(file.name.split('.')[1].toLowerCase() === self.exts){
        isJPG = true
      }
    }
    const isLt20M = file.size / 1024 / 1024 < 20;
    if (!isJPG) {
      self.$message.error('上传图片格式不正确!');
      return Promise.reject(new Error(400))
    } else {
      if (!isLt20M) {
        self.$message.error('上传头像图片大小不能超过 20MB!');
        return Promise.reject(new Error(400))
      } else {
        if (image.width > self.height || image.height > self.height) {
          self.$message.error('图片尺寸不符合规定,最大尺寸为16384*16384');
          return Promise.reject(new Error(400))
        } else {
          let [policyResponse, uploadResponse] = await
          Promise.all([
            ReportApi.getOssUploadPolicy(),
            ReportApi.createUpload( file.name, this.options.key, this.worksId)
          ])
          self.uploadFormParams.policy = policyResponse.data.policy
          self.uploadFormParams.OSSAccessKeyId = policyResponse.data.accessid
          self.uploadFormParams.callback = policyResponse.data.callback
          self.uploadFormParams.signature = policyResponse.data.signature
          self.uploadFormParams.key = uploadResponse.data.path
          self.uploadAction = policyResponse.data.host
          if (uploadResponse.data.status === true) {
          } else {
            return Promise.reject(new Error(400))
          }
        }
      }
    }
  },
  onRemove (file, fileList) {
    let vm = this
    ReportApi.deleteUploadFile(file.id).then((response) => {
      vm.$emit('removed', file)
  })
  },
  changeSort(){
    let result = []
    for(let i= 0;i<this.filelist.length;i++){
      result[i]=this.filelist[i].id
    }
    // console.log(result);
    this.$emit('changeSort',result)
  },
  onPreview(file){
    this.$alert('<img src="'+ file.url+'" style="width: 100%"/>', '查看', {
      dangerouslyUseHTMLString: true
    });
  },
  onSuccess (response, file, fileList) {
    this.$emit('uploaded', file)
    this.uploadingFile = null
  },
  onUploadProgress (e, file) {
    if (this.uploadingFile === null) {
      this.uploadingFile = {percentage: 0}
    } else {
      this.uploadingFile.percentage = Number.parseInt(e.percent)
    }
  }

  },
  watch: {
    fileList(val) {
      this.filelist = val;//新增result的watch，监听变更并同步到myResult上
    }
  },
  }
</script>
<style>
    .title{
        font-size: 16px;
    }
</style>
